package tech.runchen.gz5055.oms.common.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import java.util.Date;

/**
 * @author zzj
 */
public class TaskUtils {

    /**
     * 计算执行时间
     *
     * @param execTime
     * @return
     */
    public static long calculateTriggerTime(long execTime) {
        return System.currentTimeMillis() - execTime;
    }

    /**
     * 计算下一个周期执行时间
     *
     * @param weeks
     * @param time
     * @return
     */
    public static long calculateNextTriggerTime(String weeks, String time) {
        String[] week = weeks.split(",");
        //计算今天是周几
        int dayOfWeek = DateUtil.dayOfWeek(new Date());
        int indexOfWeek = findIndex(week, String.valueOf(dayOfWeek));
        int nextIndex = indexOfWeek + 1;
        if (nextIndex >= week.length) {
            indexOfWeek = 0;
        }
        DateTime nowTime = DateUtil.parseTimeToday(time);
        DateTime xx = DateUtil.offsetDay(nowTime, Math.abs(Integer.valueOf(week[indexOfWeek]) - dayOfWeek));
        return System.currentTimeMillis() - xx.getTime();
    }

    /**
     * 计算数组下标
     *
     * @param arr
     * @param target
     * @return
     */
    private static int findIndex(String[] arr, String target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equals(target)) {
                return i;
            }
        }
        return -1;
    }
}
